﻿using Aspose.Words;
using Aspose.Words.Saving;
using Aspose.Words.Tables;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Net;

namespace WebApplication_pdf.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet("GetPDF")]
        public async Task<IActionResult> GetPDF()
        {
            var document = await CreatePDF();
            var saveOptions = new PdfSaveOptions { SaveFormat = SaveFormat.Pdf, OpenHyperlinksInNewWindow = true };
            var docStream = new MemoryStream();
            document.Save(docStream, saveOptions);

            // 将MemoryStream转换为字节数组
            byte[] pdfBytes = docStream.ToArray();

            // 返回PDF文件作为HTTP响应
            return File(pdfBytes, "application/pdf", "generated_document.pdf");

            //string pdfname = DateTime.Now.ToString("yyyyMMddHHmmfffffff") + ".pdf";
            //var PdfPath = "PDFFolder";
            //string cDirectPath = System.AppDomain.CurrentDomain.BaseDirectory + PdfPath;
            //string pdfFullName = cDirectPath + "\\" + pdfname;

            //CreateCasePDF(docStream, pdfname, cDirectPath);

            ////HttpResponse response = new HttpResponse();
            ////response.Clear();
            ////response.ClearHeaders();
            ////response.ClearContent();
            ////response.Buffer = false;
            ////response.ContentType = "application/pdf"; // Or any other MIME type
            ////response.AddHeader("content-disposition", "inline:filename=" + pdfname);


            ////response.WriteFile(pdfFullName);
            ////response.Flush();
            ////System.IO.File.Delete(pdfFullName);
            ////response.End();
            //HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            //response.Content = new StreamContent(new MemoryStream(result));
            //PdfToBinaryConverter converter = new PdfToBinaryConverter();
            //byte[] pdfBinaryData = converter.ConvertPdfToBinary(pdfFilePath);
            //return File(fileBytes, "application/pdf", $"{pdfname}.pdf");
        }
        private async Task<Document> CreatePDF()
        {
            var document = new Document();
            var builder = new DocumentBuilder(document)
            {
                PageSetup = {
                    PageWidth = ConvertUtil.MillimeterToPoint(120),
                    PageHeight = ConvertUtil.MillimeterToPoint(241),
                    Orientation = Orientation.Landscape,
                    TopMargin = ConvertUtil.MillimeterToPoint(4),
                    BottomMargin = ConvertUtil.MillimeterToPoint(4),
                    LeftMargin = ConvertUtil.MillimeterToPoint(4),
                    RightMargin = ConvertUtil.MillimeterToPoint(4)
                }
            };
            DocumentTitle(builder, "XXXX公司");
            DocumentHead(builder);
            ProductProcessHead(builder);
            ProductProcess(builder);
            SignProcess(builder);
            return await Task.FromResult(document);
        }
        /// <summary>
        /// 标题
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="title"></param>
        private void DocumentTitle(DocumentBuilder builder, string title)
        {
            builder.CellFormat.ClearFormatting();
            builder.Font.Size = 16;
            builder.Font.NameFarEast = "黑体";
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.Writeln(title + " 销售单");
            builder.Font.Size = 12;
            builder.Font.NameFarEast = "黑体";
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
        }
        /// <summary>
        /// 表头
        /// </summary>
        /// <param name="builder"></param>
        private void DocumentHead(DocumentBuilder builder)
        {
            builder.Font.Size = 12;
            builder.StartTable();
            builder.CellFormat.ClearFormatting();
            builder.CellFormat.Borders.LineStyle = LineStyle.None;
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.CellFormat.TopPadding = Aspose.Words.ConvertUtil.MillimeterToPoint(1);
            builder.CellFormat.FitText = true;

            builder.InsertCell();
            builder.Write("进厂编号:");
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(26);
            builder.CellFormat.LeftPadding = Aspose.Words.ConvertUtil.MillimeterToPoint(1);
            builder.InsertCell();
            builder.Write("20241224001");
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(48);
            builder.CellFormat.LeftPadding = Aspose.Words.ConvertUtil.MillimeterToPoint(0);


            builder.InsertCell();
            builder.Write("");
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(60);
            builder.CellFormat.LeftPadding = Aspose.Words.ConvertUtil.MillimeterToPoint(1);

            builder.InsertCell();
            builder.Write("打印时间:");
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(26);
            builder.CellFormat.LeftPadding = Aspose.Words.ConvertUtil.MillimeterToPoint(0);
            builder.InsertCell();
            builder.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(48);
            builder.CellFormat.LeftPadding = Aspose.Words.ConvertUtil.MillimeterToPoint(0);

            builder.EndRow();

            builder.EndTable();
        }
        /// <summary>
        /// 表体表格的 表头
        /// </summary>
        /// <param name="builder"></param>
        private void ProductProcessHead(DocumentBuilder builder)
        {
            var productTable = builder.StartTable();
            productTable.SetBorders(LineStyle.None, 0d, System.Drawing.Color.White);
            builder.CellFormat.Borders.LineStyle = LineStyle.Single;
            builder.Font.NameFarEast = "黑体";
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            builder.Font.Size = 12;

            builder.EndTable();
        }
        /// <summary>
        /// 表格内容
        /// </summary>
        /// <param name="builder"></param>
        private void ProductProcess(DocumentBuilder builder)
        {
            builder.StartTable();
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("车牌号");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("京A12345");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("供货商");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("XX供货商");

            builder.EndRow();

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("进场批次");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("A01");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("产地");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("北京");

            builder.EndRow();

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("称重头数");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write(10.ToString());

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("毛重（KG）");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("150.00");

            builder.EndRow();

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("皮重（KG）");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("10.00");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("净重（KG）");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("140.00");

            builder.EndRow();

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("检疫证号");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("JY20241223001");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("扣减");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("黑猪,残疾");

            builder.EndRow();

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(50);
            builder.Write("备注");

            builder.InsertCell();
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(150);
            builder.Write("啦啦啦");

            builder.EndRow();


            builder.EndTable();
        }
        /// <summary>
        /// 页脚
        /// </summary>
        /// <param name="builder"></param>
        private void SignProcess(DocumentBuilder builder)
        {
            var signTable = builder.StartTable();
            builder.Font.Size = 12;
            builder.CellFormat.Borders.LineStyle = LineStyle.None;
            builder.RowFormat.Height = Aspose.Words.ConvertUtil.MillimeterToPoint(4);
            builder.InsertCell();
            builder.Write($"司磅人：");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(20);
            builder.InsertCell();
            builder.Write("张三");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(30);

            builder.InsertCell();
            builder.Write("");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(60);

            builder.InsertCell();
            builder.Write("供应商、送货人（签字确认）:");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(60);
            builder.InsertCell();
            builder.Write("");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.CellFormat.Width = Aspose.Words.ConvertUtil.MillimeterToPoint(30);

            builder.EndRow();
            builder.EndTable();
        }
    }
}
